<?php
/**
 * Created by PhpStorm.
 * User: gyq
 * Date: 2018/11/17
 * Time: 11:24
 */

namespace app\api\service;


use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Env;
use think\facade\Log;

include Env::get('root_path') . 'extend/wxPay/WxPay.Api.php';

class Pay
{
    private $orderID;
    private $orderNum;

    public function __construct($orderID)
    {
        if (!$orderID) {
            throw new Exception('订单ID不能为空');
        }
        $this->orderID = $orderID;
    }

    public function pay()
    {
//        拿到订单要先检测是否存在该订单信息
//        检测订单是否属于uid
//        检测订单是否已支付
        $this->checkOrderValid();
//        检测订单库存
        $orderService = new OrderService();
        $status = $orderService->checkOrderStock($this->orderID);
        if (!$status['pass']) {
            return $status;
        }
        return $this->makeWxPreOrder($status['orderPrice']);
    }

    private function makeWxPreOrder($totalPrice)
    {
        $openid = Token::getCurrentTokenVar('openid');
        if (!$openid) {
            throw new TokenException();
        }
        $wxOrderData = new \WxPayUnifiedOrder();
        $wxOrderData->SetOut_trade_no($this->orderNum);
        $wxOrderData->SetTrade_type('JSAPI');
        $wxOrderData->SetTotal_fee($totalPrice * 100);
        $wxOrderData->SetBody('零食商贩');
        $wxOrderData->SetOpenid($openid);
        $wxOrderData->SetNotify_url('http://paysdk.weixin.qq.com/notify.php');
        return $this->getPaySignature($wxOrderData);

    }

    private function getPaySignature($wxOrderData)
    {
        $config = new WxPayConfig();
        $wxOrder = \WxPayApi::unifiedOrder($config, $wxOrderData);
        if ($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS') {
            Log::record($wxOrder, 'error');
            Log::record('获取支付订单失败', 'error');
        }
        $this->recordPayOrder($wxOrder);
        $signature = $this->sign();
        return $signature;
    }

    private function sign($wxOrder)
    {
        $jsApiPayData = new \WxPayJsApiPay();
        $jsApiPayData->SetAppid(config('wx.appid'));
        $jsApiPayData->SetTimeStamp((string)time());
        $rand = md5(time() . mt_rand(0, 1000));
        $jsApiPayData->SetNonceStr($rand);
        $jsApiPayData->SetPackage('prepay_id=' . $wxOrder['prepay_id']);
        $jsApiPayData->SetSignType('md5');

        $sign = $jsApiPayData->MakeSign();
        $rawValues = $jsApiPayData->GetValues();
        $rawValues['paySign'] = $sign;
        unset($rawValues['appId']);
        return $rawValues;

    }

//    保存prepay_id用于订单购买后发起提醒用户的
    private function recordPayOrder($wxOrder)
    {
        $order = OrderModel::where('id', 'eq', $this->orderID)->find();
        $order->prepay_id = $wxOrder['prepay_id'];
        $order->save();
    }

    public function checkOrderValid()
    {
        $order = OrderModel::where('id', 'eq', $this->orderID)->find();
        if (!$order) {
            throw new OrderException();
        }
        if (!Token::isValidOperate($order->user_id)) {
            throw new TokenException([
                'msg' => '订单与用户不匹配',
                'errorcode' => 10003
            ]);
        }
        if ($order->status != OrderStatusEnum::UNPAID) {
            throw new OrderException([
                'msg' => '该订单已经支付过啦',
                'errorcode' => 80003,
                'code' => 400
            ]);
        }
        $this->orderNum = $order->order_no;
        return true;
    }
}